from django.shortcuts import render
from django.http import HttpResponse
from django.db.models import Q
# Create your views here.
from django.contrib.auth.hashers import make_password, check_password
from .. import models
from django.core.urlresolvers import reverse
from web.settings import BASE_DIR
import os
from .viewsIndex import uploads
from .viewsIndex import pages
from django.contrib.auth.decorators import permission_required


@permission_required('myadmin.show_users',raise_exception = True)
#后台正常用户列表
def userindex(request):

    #获取所有用户数据
    data = models.Users.objects.filter().exclude(status=1).exclude(status=2)#排除状态禁用和删除的
    
    #获取搜索条件和参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')
    try:
        # 判断是否有搜索条件
        if types:
            # 判断搜索的类型
            if types == 'all':
                # 多字段的条件搜索 
                # select * from users where username like '%a%' or phone like '%a%'...
                # filter(username=a,password=b) filter(username=a).filter(password=b) 并查询and
                # Q 对象  或查询or  __contains包含
                if keywords == '男':
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains='1')) 
                elif keywords == '女':
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains='0'))
                elif keywords == '保密':
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains='2'))
                else:
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords))    
            
            elif types == 'status':
                # 0 正常  1禁用  2删除 3管理
                arr = {'正常':0,'管理':3}
                data = data.filter(status=arr[keywords])

            elif types == 'sex':
                # 0 女 1 男 2 保密
                if keywords == '男':
                    data = data.filter(Q(sex__contains='1')) 
                elif keywords == '女':
                    data = data.filter(Q(sex__contains='0'))
                elif keywords == '保密':
                    data = data.filter(Q(sex__contains='2'))
            else:
                # data = data.filter(username__contains=keywords)
                # 将表单上传的名字拼接上
                search = {types+'__contains':keywords}
                data = data.filter(**search)

        #分页函数调用       
        userlist = pages(data,request)
        #分配数据
        context = {'userlist':userlist}
        return render(request,'myadmin/users/index.html',context)
    except:
        return HttpResponse('<script>alert("搜索失败,请输入正确内容");location.href="'+reverse('myadmin_user_index')+'"</script>')


@permission_required('myadmin.insert_users',raise_exception = True)
#后台会员添加显示
def useradd(request):
    #判断当前请求方式
    if request.method == 'GET':
        #加载表单页面
        return render(request,'myadmin/users/add.html')
    elif request.method == 'POST':
        try:
            #接收数据进行数据整理
            data = request.POST.dict()
            data.pop('csrfmiddlewaretoken')
            #密码加密
            data['password'] = make_password(data['password'],None,'pbkdf2_sha256')
            #头像上传
            myfile = request.FILES.get('pic_url')
            if myfile:
                #调用函数进行头像上传
                data['pic_url'] = uploads(myfile)
            else:
                data['pic_url'] = '/static/pics/user.jpg'
            #进行数据的添加
            ob = models.Users(**data)
            ob.save()

            return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
        except:
            return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_user_add')+'"</script>')



@permission_required('myadmin.del_users',raise_exception = True)
#会员删除 逻辑删除
def userdel(request,uid):
    try:
        #根据uid获取用户对象,修改状态
        ob = models.Users.objects.get(id=uid)
        ob.status = 2
        ob.save()
        return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("删除失败");location.href="'+reverse('myadmin_user_index')+'"</script>')


@permission_required('myadmin.del_users',raise_exception = True)
#删除会员列表
def userdeletelist(request):
    #获取所有用户数据
    data = models.Users.objects.filter(status=2)
    #获取搜索条件和参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    try:
            # 判断是否有搜索条件
        if types:
            # 判断搜索的类型
            if types == 'all':
                # 多字段的条件搜索 
                if keywords == '男':
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains='1')) 
                elif keywords == '女':
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains='0'))
                elif keywords == '保密':
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains='2'))
                else:
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords))
            elif types == 'sex':
                # 0 女 1 男 2 保密
                if keywords == '男':
                    data = data.filter(Q(sex__contains='1')) 
                elif keywords == '女':
                    data = data.filter(Q(sex__contains='0'))
                elif keywords == '保密':
                    data = data.filter(Q(sex__contains='2'))
            else:
                # data = data.filter(username__contains=keywords)
                # 将表单上传的名字拼接上
                search = {types+'__contains':keywords}
                data = data.filter(**search)


        #分页函数调用       
        userlist = pages(data,request)
        #分配数据
        context = {'userlist':userlist}
        return render(request,'myadmin/users/deletelist.html',context)
    except:
        return HttpResponse('<script>alert("搜索失败,请输入正确内容");location.href="'+reverse('myadmin_user_deletelist')+'"</script>')


@permission_required('myadmin.edit_users',raise_exception = True)
#显示编辑表单,执行编辑
def useredit(request,uid):
    #根据uid获取用户对象
    ob =models.Users.objects.get(id=uid)
    #判断请求方式
    if request.method == 'GET':
        #显示编辑表单
        return render(request,'myadmin/users/edit.html',{'uinfo':ob})
    elif request.method == 'POST':
        #执行编辑
        ob.username = request.POST.get('username')
        #密码判断
        if request.POST.get('password'):
            # 修改
            ob.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
        ob.phone = request.POST.get('phone')
        ob.email = request.POST.get('email')
        if request.POST.get('age') == 'None':
            ob.age = None
        ob.sex = request.POST.get('sex')
        # 判断是否更新了头像
        myfile = request.FILES.get('pic_url')
        if myfile:
            # 如果修改了头像,要上传新的头像,并判断是否删除以前头像
            if ob.pic_url != '/static/pics/user.jpg':
                # 删除原来上传的头像
                os.remove(BASE_DIR+ob.pic_url)

            # 更新头像
            ob.pic_url = uploads(myfile)
        # 执行数据的更新
        ob.save()

        return HttpResponse('<script>alert("更新成功");location.href="'+reverse('myadmin_user_index')+'"</script>')

#会员黑添加名单
def userblackadd(request,uid):
    try:
        #根据uid获取用户对象,修改状态
        ob = models.Users.objects.get(id=uid)
        ob.status = 1
        ob.save()
        return HttpResponse('<script>alert("禁用成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("禁用失败");location.href="'+reverse('myadmin_user_index')+'"</script>')         

#后台黑名单用户列表
def userblacklist(request):
    #获取所有用户数据
    data = models.Users.objects.filter(status=1)
    #获取搜索条件和参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    try:
            # 判断是否有搜索条件
        if types:
            # 判断搜索的类型
            if types == 'all':
                # 多字段的条件搜索 
                if keywords == '男':
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains='1')) 
                elif keywords == '女':
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains='0'))
                elif keywords == '保密':
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains='2'))
                else:
                    data = data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords))
            elif types == 'sex':
                # 0 女 1 男 2 保密
                if keywords == '男':
                    data = data.filter(Q(sex__contains='1')) 
                elif keywords == '女':
                    data = data.filter(Q(sex__contains='0'))
                elif keywords == '保密':
                    data = data.filter(Q(sex__contains='2'))
            else:
                # data = data.filter(username__contains=keywords)
                # 将表单上传的名字拼接上
                search = {types+'__contains':keywords}
                data = data.filter(**search)


        #分页函数调用       
        userlist = pages(data,request)
        #分配数据
        context = {'userlist':userlist}
        return render(request,'myadmin/users/blacklist.html',context)
    except:
        return HttpResponse('<script>alert("搜索失败,请输入正确内容");location.href="'+reverse('myadmin_user_blacklist')+'"</script>')

#后台还原用户
def userblackopen(request,uid):
    try:
        #根据uid获取用户对象,修改状态
        ob = models.Users.objects.get(id=uid)
        ob.status = 0
        ob.save()
        return HttpResponse('<script>alert("还原成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("还原失败");location.href="'+reverse('myadmin_user_index')+'"</script>') 